package org.snusmumr.android.media.dialog;

import org.snusmumr.android.media.R;
import org.snusmumr.android.media.bean.ItemModel;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;

public class ItemDialog extends Dialog {
	public interface ItemDialogListener {
		public void onOk (ItemModel<String> result);
	}
	
	private ItemModel<String> itemModel;
	private int titleId;
	private ItemDialogListener listener;

	public ItemDialog(int titleId, Context context, ItemModel<String> itemModel, ItemDialogListener listener) {
		super(context);
		this.titleId = titleId;
		this.listener = listener;
		setItemModel(itemModel);
	}

	public ItemDialog(int titleId, Context context, int theme, ItemModel<String> itemModel, ItemDialogListener listener) {
		super(context, theme);
		this.titleId = titleId;
		this.listener = listener;
		setItemModel(itemModel);
	}
	
	private void setItemModel(ItemModel<String> itemModel) {
		this.itemModel = itemModel == null ? new ItemModel<String>(null, null) : itemModel;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.add_simple_item_dlg);
		setTitle(titleId);
		setCancelable(false);
		
		LayoutParams params = getWindow().getAttributes(); 
	    params.width = LayoutParams.FILL_PARENT; 
	    getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
	    
	    if(itemModel.getValue() != null) {
	    	getEditText().setText(itemModel.getValue());
	    }
	    
	    Button save = (Button) findViewById(R.id.btn_add_simple_item_dlg_save);
		save.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String value = getEditText().getText().toString();
				if(value != null && value.trim().length() > 0) {
					itemModel.setValue(value);
					listener.onOk(itemModel);
					ItemDialog.this.dismiss();
				}
			}
		});
		Button canel = (Button) findViewById(R.id.btn_add_simple_item_dlg_cancel);
		canel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				ItemDialog.this.cancel();
			}
		});
	}
	
	private EditText getEditText() {
		return (EditText) findViewById(R.id.et_add_simple_item);
	}
}
